<template>
  <el-scrollbar height="100vh">
    <div class="container">
      <el-affix :offset="1">
        <h1 class="title">按限制范围加载图层</h1>
      </el-affix>
      <div id="map" class="map-x" ref="mapBox"></div>
      <el-row :gutter="10" class="select">
        <el-button type="success" @click="replaceTheRegion('India')">印度</el-button>
        <el-button type="success" @click="replaceTheRegion('Argentina')">阿根廷</el-button>
        <el-button type="success" @click="replaceTheRegion('Nigeria')">尼日利亚</el-button>
        <el-button type="success" @click="replaceTheRegion('Sweden')">瑞典</el-button>
      </el-row>
      <dl>
        <dt>设置范围</dt>
        <dd>setExtent(): 使用视图投影手动设置绘制范围。</dd>
        <dd>extent：初始范围</dd>
      </dl>
      <div class="codestyle"><Code /></div>
    </div>
  </el-scrollbar>
</template>
<script>
import { toRefs, reactive, ref, onMounted } from 'vue-demi'
import Code from './code.vue'
import 'ol/ol.css'
import { Map, View } from 'ol'
import Tile from 'ol/layer/Tile'
import BingMaps from 'ol/source/BingMaps'
import XYZ from 'ol/source/XYZ'
export default {
  setup () {
    const state = reactive({
      map: ref(null),
      mapBox: ref(null),
      India: [68.17665, 7.96553, 97.40256, 35.49401],
      Argentina: [-73.41544, -55.25, -53.62835, -21.83231],
      Nigeria: [2.6917, 4.24059, 14.57718, 13.86592],
      Sweden: [11.02737, 15.36174, 53.90338, 89.10625],
      overlay: new Tile({ // 默认显示印度
        extent: [68.17665, 7.96553, 97.40256, 35.49401],
        source: new XYZ({
          url: 'http://t4.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=ab47b4591ab6e07e0530606eca973edd'
        })
      })
    })

    const init = () => {
      state.map = new Map({
        target: state.mapBox,
        layers: [
          new Tile({
            source: new BingMaps({
              key: 'AiZrfxUNMRpOOlCpcMkBPxMUSKOEzqGeJTcVKUrXBsUdQDXutUBFN3-GnMNSlso-',
              imagerySet: 'Aerial'
            })
          }),
          state.overlay // 显示指定范围的图层
        ],
        view: new View({
          // 地图视图
          projection: 'EPSG:4326', // 坐标系，有EPSG:4326和EPSG:3857
          center: [0, 0],
          zoom: 1 // 地图缩放级别（打开页面时默认级别）
        })
      })
    }

    const replaceTheRegion = (data) => {
      state.overlay.setExtent(state[data])
    }

    onMounted(() => {
      init()
    })

    return {
      init,
      replaceTheRegion,
      ...toRefs(state)
    }
  },
  components: {
    Code
  }
}
</script>
<style lang="scss" scoped>
@import '../../css/main.scss';
.select {
  margin: 20px 0;
}
</style>
